package com.dyna.core.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.dyna.constants.SysConstant;
import com.dyna.constants.TokenConstant;
import com.dyna.core.exception.CustomException;
import com.dyna.domain.dto.LoginUser;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;

/**
 * 认证用户信息
 */
public class SecurityUtil {

    /**
     * 获取用户信息
     */
    public static LoginUser getUserInfo() {
        HttpServletRequest request = WebUtil.getRequest();
        Optional.ofNullable(request).orElseThrow(() -> new CustomException(SysConstant.REQUEST_ERROR));
        String loginUserHeader = request.getHeader(TokenConstant.LOGIN_USER_HEADER);
        if (StrUtil.isBlank(loginUserHeader)) {
            throw new CustomException(SysConstant.AUTHORIZATION_ERROR_INFO);
        }
        try {
            byte[] decodedBytes = Base64.getDecoder().decode(loginUserHeader);
            String userInfoJson = new String(decodedBytes, StandardCharsets.UTF_8);
            return JSON.parseObject(userInfoJson,  LoginUser.class);
        } catch (Exception e) {
            // 处理解码异常
            throw new CustomException(SysConstant.AUTHORIZATION_ERROR_INFO);
        }
    }

    /**
     * 获取用户id
     */
    public static Long getUserId() {
        LoginUser loginUser = getUserInfo();
        return Optional.ofNullable(loginUser).map(LoginUser::getUserId).orElseThrow(() -> new CustomException(SysConstant.AUTHORIZATION_ERROR_INFO));
    }

    /**
     * 获取token
     */
    public static String getToken() {
        HttpServletRequest request = WebUtil.getRequest();
        String headerToken = request.getHeader(TokenConstant.AUTHORIZATION);
        if (StrUtil.isBlank(headerToken)) {
            throw new CustomException(SysConstant.AUTHORIZATION_ERROR_INFO);
        }
        int index = headerToken.indexOf(TokenConstant.BEARER_SPACE);
        if (index == -1) {
            throw new CustomException(SysConstant.AUTHORIZATION_ERROR_INFO);
        }
        String token = headerToken.substring(index + 7).trim();
        return token;
    }

}
